package com.mew.chess.core.game.dyj.game.task;

import cn.hutool.core.util.RandomUtil;
import com.mew.chess.core.common.handler.ChessPushMessageUtil;
import com.mew.chess.core.game.dyj.game.DyjGameManager;
import com.mew.chess.core.game.dyj.game.DyjRoomManager;
import com.mew.chess.core.game.dyj.game.common.DyjBetType;;
import com.mew.chess.core.game.dyj.game.common.DyjLinkType;
import com.mew.chess.core.game.dyj.game.common.DyjPushCMDMapType;
import com.mew.chess.core.game.dyj.game.message.BetRecordMessage;
import com.mew.chess.core.game.dyj.game.message.PushBetMessage;
import com.mew.chess.core.game.dyj.game.message.UserMessage;
import com.mew.common.enm.UserType;
import com.zebra.common.concurrent.ZebraScheduler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * 推送机器人压注
 * @author dylin
 * @create 2021/4/22
 */
@Component
@Slf4j
public class DyjPushBetScheduleTask {
    public void robotBet(int roomId, ScheduledFuture<?> stepFuture){
        DyjRoomManager roomManager = DyjGameManager.getInstance().getController(roomId);
        if (roomManager.getLinkType() != DyjLinkType.StartBet.code() || roomManager.getRobotNumber() == 0){
            if (null != stepFuture){
                ZebraScheduler.cancelScheduled(stepFuture);
            }
            return;
        }

        //随机压注数量
        //随机压注数量 机器人人数的百分之5到10之间的人数
        int betRobotNumber=RandomUtil.randomInt(
                (int)Math.floor(roomManager.getRobotNumber()/40.0d),(int)Math.ceil(roomManager.getRobotNumber()/20.0d)+1);
        BetRecordMessage[] bets=new BetRecordMessage[betRobotNumber];
        //机器人列表
        List<UserMessage> robotList=roomManager.getPlayerList().values().stream().filter(u-> u.getUserType()==UserType.Robot.code()).collect(Collectors.toList());
        //TODO 测试 只让大玩家下注
 //       List<UserMessage> robotList=roomManager.getBigRList().values().stream().filter(u-> u.getUserType()==UserType.Robot.code()).collect(Collectors.toList());
        for (int i = 0; i < betRobotNumber; i++) {
            UserMessage robot =robotList.get(RandomUtil.randomInt(robotList.size()));
            int betType = RandomUtil.randomInt(DyjBetType.values().length);
            int betNumber = roomManager.getBetArrays()[RandomUtil.randomInt(roomManager.getBetArrays().length)];
            robot.userBet(betType,betNumber);

            bets[i]= BetRecordMessage.builder()
                    .uid(roomManager.isBigPlayer(robot.getUserId())?robot.getUserId():-1)
                    .betType(betType)
                    .betNumber(betNumber)
                    .build();
        }
        PushBetMessage pushBetMessage=roomManager.bets(bets);
        ChessPushMessageUtil.broadcastMessage(roomManager.getOnlineUser().values(), DyjPushCMDMapType.BetInfoMessage.code(),pushBetMessage);
    }
}
